//
//  DownManager.m
//  DownDemo
//
//  Created by 喂！ on 2018/11/7.
//  Copyright © 2018年 well. All rights reserved.
//

#import "DownManager.h"

@implementation DownManager

static DownManager *instance = nil;


#pragma mark - 单例模式初始化
+(DownManager *)sharedInstance
{
    if(!instance)
    {
        instance=[[self alloc] init];
    }
    return instance;
}


#pragma mark - 添加任务进入下载列表
-(void)addTaskToDownload:(NSMutableDictionary *)dic
{
    NSNumber *projectId = [dic valueForKey:@"ProjectId"];
    NSString *projectName = [dic valueForKey:@"ProjectName"];
    NSNumber *type = [dic valueForKey:@"Type"];
    
    NSPredicate *apredicate=[NSPredicate predicateWithFormat:@"SELF.ProjectId == %@",projectId];
    NSArray *downloadingArr;
    downloadingArr = [self.downloadModelArr filteredArrayUsingPredicate:apredicate];
    if (downloadingArr.count > 0) {
        return;
    }
    
    NSArray *arr = [dic valueForKey:@"DownPath"];
    LocalDownloadModel *model = [[LocalDownloadModel alloc] init];
    model.processNum = 0;
    model.Type = [type integerValue];
    model.ProjectId = [projectId integerValue];
    model.ProjectName = projectName;
    model.isDownloading = true;
    model.CurrentVersion = [[dic valueForKey:@"CurrentVersion"] integerValue];
    model.currentNum = 0;
    model.allNum = [[arr valueForKeyPath:@"@sum.Length"] longValue];
    model.showLength = [[dic valueForKey:@"FileLength"] integerValue];
    model.DownPath = arr;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self downloadWithModel:model WithType:[type integerValue]];
    });
    
    [self.downloadModelArr addObject:model];
    
}

#pragma mark - 检查本地下载进度
-(void)checkDownloadProgress:(LocalDownloadModel *)model WithType:(NSInteger)type AndOperation:(DownloadOperation *)operation
{
    NSNumber *projectId = [NSNumber numberWithInteger:model.ProjectId];
    DBProjectDownloadStatus *downloadStatus = [DBProjectDownloadStatus searchSingleWithWhere:@{@"Id":projectId,@"Type":[NSNumber numberWithInteger:type]} orderBy:nil];
    
    if (downloadStatus.Downloading == true) {
        model.currentNum = [downloadStatus.DownLength longLongValue];
    }
    else
    {
        model.currentNum = 0;
    }
}



#pragma mark - 真正下载的地方
-(void)downloadWithModel:(LocalDownloadModel *)model WithType:(NSInteger)downloadType
{
//    __block BOOL isCancel = false;
//    
//    __block DownloadOperation *operation = [DownloadOperation blockOperationWithBlock:^{
//        operation.downStatus = Downloading;
//        
//        [self checkDownloadProgress:model WithType:downloadType AndOperation:operation];
//        
//        NSNumber *projectId = [NSNumber numberWithInteger:model.ProjectId];
//        
//        for (int i = 0; i<model.DownPath.count; i++) {
//            NSMutableDictionary *zipDic = [model.DownPath objectAtIndex:i];
//            NSString *modelFilePath = [zipDic valueForKey:@"Path"];
//            //下载地址
////            NSString *httpPDFFileAddress = [NSString stringWithFormat:@"%@%@",[TOSConfig getFileWebAddress],modelFilePath];
//            NSString *httpPDFFileAddress = modelFilePath;
//            httpPDFFileAddress = [httpPDFFileAddress stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//            NSURL *url = [[NSURL alloc] initWithString:httpPDFFileAddress];
//            operation.requestUrl = url;
//            //项目文件夹
//            NSString *folderAddress = [FileTools getModelFileAddress:model.ProjectId WithType:downloadType+1];
//            //zip文件去掉后缀变成文件夹的地址
//            NSString *zipFolderAddress = [folderAddress stringByAppendingPathComponent:[[modelFilePath lastPathComponent] stringByDeletingPathExtension]];
//            //zip文件地址
//            NSString *zipFileAddress = [folderAddress stringByAppendingPathComponent:[modelFilePath lastPathComponent]];
//            BOOL status = [MainInterface downloadFileWithOperation:operation AndSavePath:zipFileAddress AndFileInfo:model];
//            
//            if (operation.isCancelled == false) {
//                if (!status) {
//                    isCancel = true;
//                    operation.downStatus = Failed;
//                    [[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadFailed" object:nil];
//                    break;
//                }
//                else
//                {
//                    if (downloadType == 0) {
//                        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
//                        [dic setValue:zipFileAddress forKey:@"ZipAddress"];
//                        [dic setValue:zipFolderAddress forKey:@"TargetAddress"];
//                        
//                        [FileUtil unzipFile:dic];
//                    }
//                    
//                    DBProjectDownloadStatus *downloadStatus = [DBProjectDownloadStatus searchSingleWithWhere:@{@"Id":projectId,@"Type":[NSNumber numberWithInteger:downloadType]} orderBy:nil];
//                    
//                    if (downloadStatus == nil) {
//                        downloadStatus = [[DBProjectDownloadStatus alloc] init];
//                        downloadStatus.Id = projectId;
//                        downloadStatus.Name = model.ProjectName;
//                        downloadStatus.CurrentVersion = 0;
//                        downloadStatus.FileLength = [NSNumber numberWithInteger:model.showLength];
//                        downloadStatus.Type = downloadType;
//                    }
//                    downloadStatus.DownLength = [NSNumber numberWithLongLong:model.currentNum];
//                    
//                    [downloadStatus saveToDB];
//                    
//                }
//            }
//            else
//            {
//                isCancel = true;
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadFailed" object:nil];
//                break;
//            }
//        }
//        
//        
//        if (!isCancel) {
//            DBProjectDownloadStatus *downloadStatus = [DBProjectDownloadStatus searchSingleWithWhere:@{@"Id":projectId,@"Type":[NSNumber numberWithInteger:downloadType]} orderBy:nil];
//            
//            if (downloadStatus == nil) {
//                downloadStatus = [[DBProjectDownloadStatus alloc] init];
//                downloadStatus.Id = projectId;
//                downloadStatus.Name = model.ProjectName;
//            }
//            downloadStatus.FileLength = [NSNumber numberWithInteger:model.showLength];
//            downloadStatus.DownLength = [NSNumber numberWithInteger:0];
//            downloadStatus.CurrentVersion = model.CurrentVersion;
//            downloadStatus.Downloading = false;
//            downloadStatus.Type = downloadType;
//            [downloadStatus saveToDB];
//            
//            NSPredicate *apredicate=[NSPredicate predicateWithFormat:@"SELF.ProjectId == %@",projectId];
//            
//            NSArray *downloadingArr = [self.downloadModelArr filteredArrayUsingPredicate:apredicate];
//            if (downloadingArr.count > 0) {
//                [self.downloadModelArr removeObject:downloadingArr[0]];
//            }
//
//            
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadFinish" object:nil];
//        }
//    }];
//    
//    model.operation = operation;
//    operation.downStatus = Waiting;
//
//    [self.downloadQueue addOperation:operation];

}


#pragma mark    懒加载
-(NSMutableArray *)downloadModelArr
{
    if (!_downloadModelArr) {
        _downloadModelArr = [NSMutableArray array];
    }
    return _downloadModelArr;
}

@end
